<?php

namespace Iwester\Http\Controllers\Admin\Seo;

use Iwester\Http\Controllers\Admin\BaseController;
use App\Console\Commands\SiteMap;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;
use Iwester\Http\Model\Config\SiteConfig;
use Iwester\Http\Model\Config\SiteLink;


class AdminSeoLinkController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * 友情链接列表
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function sitelink()
    {
        $siteLinks = SiteLink::oldest('sort')->get();
        return view('iwester::admin.seo.sitelink.sitelink', ['siteLinks' => $siteLinks]);
    }

    /**
     * 新增或编辑友情链接
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id = 0)
    {
        $link = $id == 0 ? false : SiteLink::find($id);
        return view('iwester::admin.seo.sitelink.edit', ['link' => $link]);
    }

    /**
     * 保存友链
     * @param Request $request
     */
    public function store(Request $request)
    {
        try {
            \DB::beginTransaction();
            $seo = $request->get('seo', false);
            $id = $request->get('id', false);
            $seo['status'] = $seo['status'] == 'on' ? 1 : 0;
            $link = new SiteLink();
            if ($id) {
                $link = SiteLink::find($id);
                $link->update($seo);
            } else {
                $link = new SiteLink();
                $link->create($seo);
            }
            \DB::commit();
            return ['code' => 200, 'message' => '设置成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => '保存失败！'];
        }
    }

    /**
     * 删除友链
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function destroy($id = 0 )
    {
        try {
            \DB::beginTransaction();
            SiteLink::find($id)->delete();
            \DB::commit();
            return ['code' => 200, 'message' => '设置成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }
}
